package xjh.him.common;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class MyViewHolder {
    private SparseArray<View> views;
    private View item;
    private int pos;

    private MyViewHolder(Context ctx, ViewGroup parent, int layoutRes) {
        views = new SparseArray<>();
        item = LayoutInflater.from(ctx).inflate(layoutRes, parent, false);
        item.setTag(this);
    }

    public static MyViewHolder bind(int pos, View convertView, ViewGroup parent,
                                    int layoutRes) {
        MyViewHolder holder;
        if (convertView == null) {
            holder = new MyViewHolder(parent.getContext(), parent, layoutRes);
        }else {
            holder = (MyViewHolder) convertView.getTag();
            holder.item = convertView;
        }
        holder.pos = pos;
        return holder;
    }

    /**
     * get subView from view
     * @param id
     * @return
     */
    public View getView(int id) {
        View v = views.get(id);
        if (v == null) {
            v = item.findViewById(id);
            views.put(id, v);
        }
        return v;
    }

    public View getItemView() {
        return item;
    }

    public int getPos() {
        return pos;
    }
}
